const Promise = require('bluebird');
const moment = require('moment');

/**
 * @api {get} /api/admin/v1/texts/browse 用户文本
 */
exports.browse = function ({query}, {models: {UsersTexts, Users, associations}, cache: {settings}, controller}) {
    let pagination = controller.pagination({
        params: query,
        filters: ['openid'],
        likes: ['text']
    });
    return UsersTexts.findAndCountAll(pagination).then(function (data) {
        let rows = data.rows, openids = [];
        if (rows && rows.length) {
            for (let i in rows) {
                let row = rows[i];
                openids.push(row.openid);
            }
            return Users.findAll({
                where: {openid: openids},
                attributes: ['id', 'openid', 'image', 'nickname', 'username', 'nickname', 'tel'],
                raw: true
            }).then(function (users) {
                let map = {};
                for (let i in users) {
                    let user = users[i];
                    map[user.openid] = user;
                }
                for (let i in rows) {
                    let row = rows[i];
                    if (map[row.openid]) {
                        row.user = map[row.openid];
                    }
                }
                return data;
            });
        }
        return data;
    });
}